<?php
/*
Plugin Name: joomlauth Plugin for Wordpress
Plugin URI: 
Description: Share users with joomla database
Version: 0.9.1
Author: Heriniaina Eugene
Author URI: http://hery.serasera.org


NB: This version now works for Joomla 1.0.x and 1.5.x
This version only works for  wp < 2.5
Check for joomlauth.php version > 1 for wp > 2.5

Todo: shared session
*/

// *** Begin Admin Config Functions *** //

$joomlauthVersion = "0.9.1";

add_action('signup_header', 'joomlauth_signup_header');
function joomlauth_signup_header() {
	if($redirect = get_site_option("joomlauthSignupURL")) {
		echo "
			<script language=\"javascript\"
			type=\"text/javascript\">
			<!--
			window.location.replace(
			\"$redirect\");
			-->
			</script>
		";
		exit;
	}

	if($_GET['loggedout'] == "true") {
		$redirect = get_site_option("joomlauthLogoutURL");
		if(isset($redirect)) {
			echo "
				<script language=\"javascript\"
				type=\"text/javascript\">
				<!--
				window.location.replace(
				\"$redirect\");
				-->
				</script>
			";
			exit;
		}
	}
}

add_action('admin_menu', 'joomlauth_addmenu');
function joomlauth_addmenu() {
	$objCurrUser = wp_get_current_user();
	$objUser = wp_cache_get($objCurrUser->id, 'users');
	if (function_exists('add_options_page') && is_site_admin($objUser->user_login)) {
		add_options_page('Authentication Options', 'Joomla Auth Options', 9, basename(__FILE__), 'joomlauthOptionsPanel');
	}
}
require_once( ABSPATH . WPINC . '/registration.php');

function joomlauth_Auth($username, $password) {
	global $wpdb;

	$joomlauthDbHost 		= get_site_option("joomlauthDbHost");
	$joomlauthDbUser 		= get_site_option("joomlauthDbUser");
	$joomlauthDbName		= get_site_option("joomlauthDbName");
	$joomlauthDbPass		= get_site_option("joomlauthDbPass");
	$joomlauthDbPrefix		= get_site_option("joomlauthDbPrefix");

	

	$link = mysql_connect($joomlauthDbHost, $joomlauthDbUser, $joomlauthDbPass, true) or die('Not connected : ' . mysql_error());

	// make foo the current db
	$mydb = mysql_select_db($joomlauthDbName, $link) or die ('Can\'t use $joomlauthDbName : ' . mysql_error());
	
	//get by username
	$sql = "SELECT name, username, password, email FROM " . $joomlauthDbPrefix . "users WHERE LOWER(username)='" . mysql_real_escape_string(strtolower($username)) . "' LIMIT 1";
	
	if($result = mysql_query($sql)) { 
		while ($row = mysql_fetch_array($result)) {
			//get joomla password to verify if it is joomla 1.5.x or 1.0.x
			$_salt = "";
			$_parts = "";

			$_parts	= (strlen($row["password"]) > 32) ? explode( ':', $row["password"] ) : array();
			$_salt = $_parts[1];
			$_crypt		=	md5( $password . $_salt );
			$_hashedPwd	=	$_crypt. ($_salt ? ':' . $_salt : '');

			if($_hashedPwd == $row["password"]) {
				return $row;
			} else {
				Return false;
			}
			
		}
	} else {
		Return false;
	}


}
function joomlauthOptionsPanel() {
	global $joomlauthVersion;
	if($_POST['joomlauthOptionsSave']) {
		update_site_option('joomlauthSignupURL', $_POST['joomlauthSignupURL']);
		update_site_option('joomlauthLogoutURL', $_POST['joomlauthLogoutURL']);
		update_site_option('joomlauthDbHost', $_POST['joomlauthDbHost']);
		update_site_option('joomlauthDbUser', $_POST['joomlauthDbUser']);
		update_site_option('joomlauthDbName', $_POST['joomlauthDbName']);
		update_site_option('joomlauthDbPass', $_POST['joomlauthDbPass']);
		update_site_option('joomlauthDbPrefix', $_POST['joomlauthDbPrefix']);
		update_site_option('joomlauthActive', $_POST['joomlauthActive']);
		update_site_option('joomlauthGetBlog', $_POST['joomlauthGetBlog']);

		echo "<div class='updated'><p>Saved Options!</p></div>";
	}
	
	$joomlauthSignupURL 	= get_site_option("joomlauthSignupURL");
	$joomlauthLogoutURL 	= get_site_option("joomlauthLogoutURL");
	$joomlauthDbHost 		= get_site_option("joomlauthDbHost");
	$joomlauthDbUser 		= get_site_option("joomlauthDbUser");
	$joomlauthDbName		= get_site_option("joomlauthDbName");
	$joomlauthDbPass		= get_site_option("joomlauthDbPass");
	$joomlauthDbPrefix		= get_site_option("joomlauthDbPrefix");
	$joomlauthActive		= get_site_option("joomlauthActive");
	$joomlauthGetBlog		= get_site_option("joomlauthGetBlog");

	if($joomlauthActive == '1') {
		$tChecked = "checked";
	}
	else {
		$fChecked = "checked";
	}

	if($joomlauthGetBlog == '1') {
		$joomlauthGetBlog1 = "checked";
	} else {
		$joomlauthGetBlog0 = "checked";
	}
	
	echo <<<joomlauthForm
	<div class="wrap">
	<h2>joomlauth Authentication Options</h2>
		<small>Version: $joomlauthVersion : <a href="http://hery.blaogy.org/2008/02/22/joomla-user-auth-for-wordpress-mu/">Click here for update</a></small>
	<form method="post" id="joomlauth_options">

	<p class="submit"><input type="submit" value="Save" name="Submit"/></p>

		<fieldset class="options">
		<legend>Authentication options</legend>
	
		<table class="optiontable">
			<tbody>
				<tr valign="top">
					<th scope="row">Database host:</th>
					<td>
					<input type='text' name='joomlauthDbHost' value='$joomlauthDbHost' style='width: 300px;' /><br />
					<em>This is usually 'localhost'.</em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Database username:</th>
					<td>
					<input type='text' name='joomlauthDbUser' value='$joomlauthDbUser' style='width: 300px;' /><br />
					<em>Username to access the database.</em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Database password:</th>
					<td>
					<input type='password' name='joomlauthDbPass' value='$joomlauthDbPass' style='width: 300px;' /><br />
					<em>Your database password.</em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Database name:</th>
					<td>
					<input type='text' name='joomlauthDbName' value='$joomlauthDbName' style='width: 300px;' /><br />
					<em>Name of the database where users are stored.</em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Database table prefix:</th>
					<td>
					<input type='text' name='joomlauthDbPrefix' value='$joomlauthDbPrefix' style='width: 300px;' /><br />
					<em>Prefix of joomla tables example jos_ .</em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Sign-up URL:</th>
					<td>
					<input type='text' name='joomlauthSignupURL' value='$joomlauthSignupURL' style='width: 300px;' /><br />
					<em>Where people go to sign up</em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Logout URL:</th>
					<td>
					<input type='text' name='joomlauthLogoutURL' value='$joomlauthLogoutURL' style='width: 300px;' /><br />
					<em>Where users are redirected when logged out</em>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Should user get a blog?</th>
					<td>
						<input type='radio' name='joomlauthGetBlog' value='1' $joomlauthGetBlog1/> Yes <br />
						<input type='radio' name='joomlauthGetBlog' value='0' $joomlauthGetBlog0/> No account only
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">Enable joomlauth plugin?</th>
					<td>
						<input type='radio' name='joomlauthActive' value='1' $tChecked/> Yes <br />
						<input type='radio' name='joomlauthActive' value='0' $fChecked/> No 
					</td>
				</tr>
			</tbody>
		</table>
		</fieldset>
 		<p class="submit"><input type="submit" name="joomlauthOptionsSave" value="Save" /></p>
	</form>
	</div>
joomlauthForm;
}
// *** End Admin Config Functions *** //


// *** Begin User Auth Functions *** //

// This will disabled the change password dialogs.

if (get_site_option("joomlauthActive")) : 
add_filter('show_password_fields', 'getFalse');
function getFalse() {
	return false;
}
endif;

if (get_site_option("joomlauthActive")) {
add_action('wp_login', 'wp_login');
function wp_login($username, $password, $already_md5 = false) {
	global $wpdb, $error, $current_site, $current_user, $base;
	
	//Make sure we always use lowercase usernames.
	$username = strtolower($username);
	
	$joomlauthActive 		= get_site_option("joomlauthActive");
	$joomlauthSignupURL 	= get_site_option("joomlauthSignupURL");
	$joomlauthLogoutURL 	= get_site_option("joomlauthLogoutURL");
	$joomlauthDbHost 		= get_site_option("joomlauthDbHost");
	$joomlauthDbUser 		= get_site_option("joomlauthDbUser");
	$joomlauthDbName		= get_site_option("joomlauthDbName");
	$joomlauthDbPass		= get_site_option("joomlauthDbPass");
	$joomlauthDbPrefix		= get_site_option("joomlauthDbPrefix");
	$joomlauthGetBlog		= get_site_option("joomlauthGetBlog");
	
	if(!$username) {
		$error = __('<strong>Error</strong>: The username field is empty.');
		return false;
	}
	
	if(!$password) {
		$error = __('<strong>Error</strong>: The password field is empty.');
		return false;
	}

	//Bassically if we are already logged in and we try to relogin.
	if ($current_user->data->user_login == $username) {
		return true;
	}
	$login = get_userdatabylogin($username);


	//everything is ok
	
	if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
		return true;
	}
	
	//only username is ok => check from external and update the password
	if($login->user_login == $username) {
		if($juser = joomlauth_Auth($username, $password)) {
			if($juser['username'] == $username) { //just doublechecking
				$query = "UPDATE $wpdb->users SET user_pass='" . md5($password) . "' WHERE ID = '$login->ID'";
				$query = apply_filters('update_user_query', $query);
				$wpdb->query( $query );
				Return true;
			} else {
				$error = __('<strong>Error</strong>: Wrong password.');
				return false;
			}
		}
	} else {
		// a complete new user from the external database
		if($juser = joomlauth_Auth($username, $password)) {	

			// call the registration function to create a wordpress user account for this
			// successfully authenticated user
			require_once( ABSPATH . WPINC . '/registration.php');
				
			if ( !username_exists( $username ) ) { //no need of this???
				//Create the user
				//$sPassword = generate_random_password();
				define( "WP_INSTALLING", true );
				$user_id = wpmu_create_user( $username, $password, $juser[email] );
				
				if (!$user_id) {
					$error = __('<strong>Error</strong>: Account Creation Failed.');
					return false;
				}
				
				//Update their first and last name from ldap

				update_usermeta( $user_id, 'last_name', ($juser[name] ? $juser[name] : $username ));
					
				//This is for plugin events
				do_action( 'wpmu_new_user', $user_id );
				do_action('wpmu_activate_user', $user_id, $password);
					
				$domain = strtolower( wp_specialchars( $username ) );
				if( constant( "VHOST" ) == 'yes' ) {
					$newdomain = $domain . "." . $current_site->domain;
					$path = $base;
				} else {
					$newdomain = $current_site->domain;
					$path = $base . $domain . '/';
				}
					

				if (get_site_option("joomlauthGetBlog")) {
					//create blog
					$meta = apply_filters('signup_create_blog_meta', array ( 'public' => 1));
					$blog_id = wpmu_create_blog($newdomain, $path, $username , $user_id, $meta); do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $username, $meta); 
				}

				//Must recreated the login object for our shiny NEW users.
				$login = get_userdatabylogin($username);
				
				//Setup redirection to users home directory.
				if (!strpos($_REQUEST['redirect_to'], $username)) {
					$_REQUEST['redirect_to'] = $username . "/" . $_REQUEST['redirect_to'];
				}
				Return true;
			} elseif ( !username_exists( $username ) && !$seraseraCreateAcct ) {
				$error = __('<strong>Error</strong>: Local account does not exist.');
				return false;
			}

		} else {
			$error = __('<strong>Error</strong>: Wrong login and password.');
			return false;
		}
		
				
		//At this point we must have a login object!
		//I dont see how we couldn't but just in case.
		if (!$login) {
			$error = __('<strong>Error</strong>: Unknown Near ' . __LINE__ . ' in ' . __FILE__ );
			return false;
		}
		
		//Added to atempt to recreate login correctly
		//I think this is for account suspentions
		$primary_blog = get_usermeta( $login->ID, "primary_blog" );
		if( $primary_blog ) {
			$details = get_blog_details( $primary_blog );
			if( is_object( $details ) ) {
				if( $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) {
					$error = __('<strong>Error</strong>: Blog suspended.');
					return false;
				}
			}
		}
				

		// Bad Coding Practiace
		// We can get to this point in code and exit without a status.
		// This is why we dont exit at multipul points boys and girls.
		return false;
	} // End if ()

		//We are Not using LDAP So we need to auth normally 
		//This is all original code pulled from the pluggable.php 
		//file located in the wp-plugins folder.  Comments were 
		//added to help figure out what is going on.
		
		//Now I think this is trying to get the users data. 
		//I think the site admin and domain admins are stored 
		//seperatly from normal users??? Just guessing as there 
		//is NO DOCUMENTATION!!!
		//This entire code block seems a bit useless to me.  Definitly not needed if we use ldap.
		if (!$login) {
			if( is_site_admin( $username ) ) {
				//If Site Admin
				//FYI This does exactly the same thing as $login = get_userdatabylogin( $username );
				//which has already been done above?!?
				unset( $login );
				$userdetails = get_userdatabylogin( $username );
				$login->user_login = $username;
				$login->user_pass = $userdetails->user_pass;
			} else {
				//If Domain Admin
				$admins = get_admin_users_for_domain();
				reset( $admins );
				while( list( $key, $val ) = each( $admins ) ) 
				{ 
					if( $val[ 'user_login' ] == $username ) {
						unset( $login );
						$login->user_login = $username;
						$login->user_pass  = $val[ 'user_pass' ];
					}
				}
			}
		}
		
		if (!$login) {
			//If we didnt find a user originally and we didnt get one from the above code...
			$error = __('<strong>Error</strong>: Wrong username.');
			return false;
		} else {
			//Setup some kind of default blog for the user...
			$primary_blog = get_usermeta( $login->ID, "primary_blog" );
			if( $primary_blog ) {
				$details = get_blog_details( $primary_blog );
				if( is_object( $details ) ) {
					if( $details->archived == 1 || $details->spam == 1 || $details->deleted == 1 ) {
						$error = __('<strong>Error</strong>: Blog suspended.');
						return false;
					}
				}
			}
			
			//Setup redirection to users home directory.
			if (!strpos($_REQUEST['redirect_to'], $username)) {
				$_REQUEST['redirect_to'] = $username . "/" . $_REQUEST['redirect_to'];
			}
			
			// If the password is already_md5, it has been double hashed.
			// Otherwise, it is plain text.
			if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
				return true;
			} else {
				$error = __('<strong>Error</strong>: Incorrect password.');
				$pwd = '';
				return false;
			}
		}
	}
}
?>